package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet("/servletDemo2")
public class servletDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1根据名称获取数据 getParameter()
        String username = req.getParameter("username");
        System.out.println(username);
        String password = req.getParameter("password");
        System.out.println(password);
        System.out.println("-----------------");
        //2根据名称获取所有数据getParameterValues);
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {
            System.out.println(hobby);
        }
        System.out.println("-----------------");
        //3获取所有名称 getParameterNames();
        Enumeration<String> names = req.getParameterNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            System.out.println(name);
            if("hobby".equals(name)){
                String[] values = req.getParameterValues(name);
                for (String value : values) {
                    System.out.println(name+"-"+value);
                }
            }else {
                String value = req.getParameter(name);
                System.out.println(name+"-"+value);
            }
        }
        System.out.println("-----------------");
        //4获取所有参数的键值对getParameterMap();
        Map<String, String[]> pm = req.getParameterMap();
        //Set集合:用增强for遍历Set集合
        //Set<String> set = pm.keySet();
        for(String key:pm.keySet()){
            String[] values = pm.get(key);
            System.out.print(key+":");
            for (String value : values) {
                System.out.print(value+" ");
            }
            System.out.println();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
